package com.wd.health.view.activity.mine;

import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.baidu.ocr.ui.camera.CameraNativeHelper;
import com.baidu.ocr.ui.camera.CameraView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gyf.immersionbar.ImmersionBar;
import com.wd.health.R;
import com.wd.health.model.bean.MessageStatusBean;
import com.wd.health.utils.FileUtil;
import com.wd.health.utils.RetrofitManager;
import com.wd.health.utils.RsaCoder;

import java.io.File;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class MissionCertificationActivity extends AppCompatActivity {

    private ImageView img_back;
    private RelativeLayout rl_rxm;
    private RelativeLayout rl_ghm;
    private boolean hasGotToken = false;
    private AlertDialog.Builder alertDialog;
    private static final int REQUEST_CODE_PICK_IMAGE_FRONT = 201;
    private static final int REQUEST_CODE_PICK_IMAGE_BACK = 202;
    private static final int REQUEST_CODE_CAMERA = 102;
    private SimpleDraweeView sdv_zheng;
    private SimpleDraweeView sdv_bei;
    private SharedPreferences sfz;
    private Button btn_next;
    private TextView tv_name;
    private TextView tv_gender;
    private TextView tv_ethnic;
    private TextView tv_birthday;
    private TextView tv_address;
    private TextView tv_isnumber;
    private ImageView img_shexiang01;
    private TextView tv_rxm;
    private ImageView img_shexiang02;
    private TextView tv_ghm;
    private TextView tv_fxjg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mission_certification);
        //  初始化本地质量控制模型,释放代码在onDestory中
        //  调用身份证扫描必须加上 intent.putExtra(CameraActivity.KEY_NATIVE_MANUAL, true); 关闭自动初始化和释放本地模型
        CameraNativeHelper.init(this, OCR.getInstance(this).getLicense(),
                new CameraNativeHelper.CameraNativeInitCallback() {
                    @Override
                    public void onError(int errorCode, Throwable e) {
                        String msg;
                        switch (errorCode) {
                            case CameraView.NATIVE_SOLOAD_FAIL:
                                msg = "加载so失败，请确保apk中存在ui部分的so";
                                break;
                            case CameraView.NATIVE_AUTH_FAIL:
                                msg = "授权本地质量控制token获取失败";
                                break;
                            case CameraView.NATIVE_INIT_FAIL:
                                msg = "本地质量控制";
                                break;
                            default:
                                msg = String.valueOf(errorCode);
                        }
                        Log.e("TAG", msg);
                    }
                });
        alertDialog = new AlertDialog.Builder(this);
        initAccessTokenWithAkSk();
//        initAccessTokenLicenseFile();
        initView();
    }

    private void initAccessTokenWithAkSk() {
        OCR.getInstance(this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                hasGotToken = true;
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                alertText("AK，SK方式获取token失败", error.getMessage());
            }
        }, getApplicationContext(),  "zGgXZaxbN4xNXMRjppBXhxy6", "5o6GEEZFgSPaWvkDOVtRADFSf9GGmH04");
    }

    private void initAccessTokenLicenseFile() {
        OCR.getInstance(this).initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                String token = accessToken.getAccessToken();
                hasGotToken = true;
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                alertText("自定义文件路径licence方式获取token失败", error.getMessage());
            }
        }, "aip.license", getApplicationContext());
    }

    private void initView() {
        img_back = findViewById(R.id.img_back);
        rl_rxm = findViewById(R.id.rl_rxm);
        rl_ghm = findViewById(R.id.rl_ghm);
        sdv_zheng = findViewById(R.id.sdv_zheng);
        sdv_bei = findViewById(R.id.sdv_bei);
        btn_next = findViewById(R.id.btn_next);
        tv_name = findViewById(R.id.tv_name);
        tv_gender = findViewById(R.id.tv_gender);
        tv_ethnic = findViewById(R.id.tv_ethnic);
        tv_birthday = findViewById(R.id.tv_birthday);
        tv_address = findViewById(R.id.tv_address);
        tv_isnumber = findViewById(R.id.tv_isnumber);
        img_shexiang01 = findViewById(R.id.img_shexiang01);
        img_shexiang02 = findViewById(R.id.img_shexiang02);
        tv_rxm = findViewById(R.id.tv_rxm);
        tv_ghm = findViewById(R.id.tv_ghm);
        tv_fxjg = findViewById(R.id.tv_fxjg);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btn_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initBangDing();
            }
        });

        rl_rxm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MissionCertificationActivity.this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_NATIVE_ENABLE,
                        true);
                // KEY_NATIVE_MANUAL设置了之后CameraActivity中不再自动初始化和释放模型
                // 请手动使用CameraNativeHelper初始化和释放模型
                // 推荐这样做，可以避免一些activity切换导致的不必要的异常
                intent.putExtra(CameraActivity.KEY_NATIVE_MANUAL,
                        true);
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
                startActivityForResult(intent, REQUEST_CODE_CAMERA);
            }
        });

        rl_ghm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MissionCertificationActivity.this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_NATIVE_ENABLE,
                        true);
                // KEY_NATIVE_MANUAL设置了之后CameraActivity中不再自动初始化和释放模型
                // 请手动使用CameraNativeHelper初始化和释放模型
                // 推荐这样做，可以避免一些activity切换导致的不必要的异常
                intent.putExtra(CameraActivity.KEY_NATIVE_MANUAL,
                        true);
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_BACK);
                startActivityForResult(intent, REQUEST_CODE_CAMERA);
            }
        });
    }

    private void initBangDing() {
        SharedPreferences user = getSharedPreferences("user", Context.MODE_PRIVATE);
        int userId = user.getInt("userId", 0);
        String name = sfz.getString("name", "");
        String address = sfz.getString("address", "");
        String idNumber = sfz.getString("idNumber", "");
        String birthday = sfz.getString("birthday", "");
        String gender = sfz.getString("gender", "");
        String ethnic = sfz.getString("ethnic", "");
        String issueAuthority = sfz.getString("issueAuthority", "");
        try {
            String s1 = RsaCoder.encryptByPublicKey(name);
            String s2 = RsaCoder.encryptByPublicKey(gender);
            String s3 = RsaCoder.encryptByPublicKey(ethnic);
            String s4 = RsaCoder.encryptByPublicKey(birthday);
            String s5 = RsaCoder.encryptByPublicKey(address);
            String s6 = RsaCoder.encryptByPublicKey(idNumber);
            String s7 = RsaCoder.encryptByPublicKey(issueAuthority);
            RetrofitManager.getInstance().postSfzData(userId, s1, s2, s3, s4, s5, s6, s7, new Observer<MessageStatusBean>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(MessageStatusBean messageStatusBean) {
                    if (messageStatusBean.getStatus().equals("0000")){
                        Toast.makeText(MissionCertificationActivity.this, "绑定成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void recIDCard(String idCardSide, String filePath) {
        IDCardParams param = new IDCardParams();
        param.setImageFile(new File(filePath));
        // 设置身份证正反面
        param.setIdCardSide(idCardSide);
        // 设置方向检测
        param.setDetectDirection(true);
        // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
        param.setImageQuality(20);

        OCR.getInstance(this).recognizeIDCard(param, new OnResultListener<IDCardResult>() {
            @Override
            public void onResult(IDCardResult result) {
                if (result != null) {
                    tv_rxm.setVisibility(View.GONE);
                    img_shexiang01.setVisibility(View.GONE);
                    tv_name.setVisibility(View.VISIBLE);
                    tv_gender.setVisibility(View.VISIBLE);
                    tv_ethnic.setVisibility(View.VISIBLE);
                    tv_birthday.setVisibility(View.VISIBLE);
                    tv_address.setVisibility(View.VISIBLE);
                    tv_isnumber.setVisibility(View.VISIBLE);
                    sfz = getSharedPreferences("sfz", Context.MODE_PRIVATE);

                    String name = String.valueOf(result.getName());
                    String address = String.valueOf(result.getAddress());
                    String idNumber = String.valueOf(result.getIdNumber());
                    String birthday = String.valueOf(result.getBirthday());
                    String gender = String.valueOf(result.getGender());
                    String ethnic = String.valueOf(result.getEthnic());
                    String issueAuthority = String.valueOf(result.getIssueAuthority());

                    tv_name.setText("姓名:"+name);
                    tv_gender.setText("男:"+gender);
                    tv_ethnic.setText("民族:"+ethnic);
                    tv_birthday.setText("出生日期:"+birthday);
                    tv_address.setText("家庭住址:"+address);
                    tv_isnumber.setText("身份证号:"+idNumber);
                    tv_fxjg.setText("发行机关:"+issueAuthority);
                    sfz.edit()
                            .putString("name",name)
                            .putString("address",address)
                            .putString("idNumber",idNumber)
                            .putString("birthday",birthday)
                            .putString("gender",gender)
                            .putString("ethnic",ethnic)
                            .putString("issueAuthority",issueAuthority)
                            .commit();
                    alertText("", result.toString());
                }
            }

            @Override
            public void onError(OCRError error) {
                alertText("", error.getMessage());
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_PICK_IMAGE_FRONT && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            String filePath = getRealPathFromURI(uri);
            recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
        }

        if (requestCode == REQUEST_CODE_PICK_IMAGE_BACK && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            String filePath = getRealPathFromURI(uri);
            recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);
        }

        if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE);
                String filePath = FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath();
                if (!TextUtils.isEmpty(contentType)) {
                    if (CameraActivity.CONTENT_TYPE_ID_CARD_FRONT.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
                    } else if (CameraActivity.CONTENT_TYPE_ID_CARD_BACK.equals(contentType)) {
                        recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);
                    }
                }
            }
        }
    }

    private void alertText(final String title, final String message) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                alertDialog.setTitle(title)
                        .setMessage(message)
                        .setPositiveButton("确定", null)
                        .show();
            }
        });
    }

    private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
        if (cursor == null) { // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }

    private boolean checkTokenStatus() {
        if (!hasGotToken) {
            Toast.makeText(getApplicationContext(), "token还未成功获取", Toast.LENGTH_LONG).show();
        }
        return hasGotToken;
    }

    @Override
    protected void onDestroy() {
        // 释放本地质量控制模型
        CameraNativeHelper.release();
        super.onDestroy();
    }
}